import { Component, OnInit } from '@angular/core';

import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';

import { FinanceAfterSaleDetailService } from './finance-after-sale-detail.service';
import { DatePipe } from '@angular/common';
import { CommonService } from 'src/app/services-common/common.service';
import { PermissionService } from '../../../service/permission.service';

@Component({
  selector: 'app-finance-after-sale-detail',
  templateUrl: './finance-after-sale-detail.component.html',
  styleUrls: ['./finance-after-sale-detail.component.scss'],
  providers: [DatePipe]
})
export class FinanceAfterSaleDetailComponent implements OnInit {
  // 搜索条件
  queryForms: any = {
    stateList: [], // 状态
    createTime: [], // 申请时间
    refundTime: [], // 收款时间
    payType: '', // 平台
    supplierId: [], // 货主
    payOrderNum: '' // 交易流水
  };
  // table
  tableForms: any = {
    tableLoading: false,
    pageIndex: 1,
    pageSize: 20,
    total: 0
  };
  // tableData
  tableData: any = [];
  // 状态：0-用户提交申请（待审核）、1-审核通过（待买家退货）、2-退货超时、3-商品已寄出、4-待平台审核、5-发起退款操作或直接退款、6-售后成功、7-售后失败、8-已取消
  statusArrys: any = [{
    id: 0,
    title: '用户提交申请（待审核）'
  }, {
    id: 1,
    title: '审核通过（待买家退货）'
  }, {
    id: 2,
    title: '退货超时'
  }, {
    id: 3,
    title: '商品已寄出'
  }, {
    id: 4,
    title: '待平台审核'
  }, {
    id: 5,
    title: '发起退款操作或直接退款'
  }, {
    id: 6,
    title: '售后成功'
  }, {
    id: 7,
    title: '售后失败'
  }, {
    id: 8,
    title: '已取消'
  }];

  // model
  isVisible: boolean = false;
  // model title (订单号)
  modelTitle: string = '';
  // modelTabe
  modelTableData: any = [];

  // 货主options（供应商）
  supplierOptions: any = [];

  exportLoading: boolean = false;

  constructor(
    private message: NzMessageService,
    private service: FinanceAfterSaleDetailService,
    private datePipe: DatePipe,
    private commonService: CommonService,
    public permission: PermissionService,
    private modal: NzModalService
  ) { }

  ngOnInit() {
    this.querySupplierOptions();
    this.loadTableData();
  }

  // 查询货主
  async querySupplierOptions() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const res: any = await this.commonService.querySupplierList(params);
    if (res.code === 0) {
      const { records } = res.data || {};
      this.supplierOptions = records.filter((item: any) => item.name) || [];
    } else {
      this.message.error(res.message);
    }
  }

  // 日期格式
  formatDate(date?: any) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }

  // loadTableData
  loadTableData() {
    let datas: any = {
      stateList: this.queryForms.stateList,
      createTimeStart: this.queryForms.createTime.length ? this.formatDate(this.queryForms.createTime[0]) : '',
      createTimeEnd: this.queryForms.createTime.length ? this.formatDate(this.queryForms.createTime[1]) : '',
      refundCreateTime: this.queryForms.refundTime.length ? this.formatDate(this.queryForms.refundTime[0]) : '',
      refundEndTime: this.queryForms.refundTime.length ? this.formatDate(this.queryForms.refundTime[1]) : '',
      payType: this.queryForms.payType,
      payOrderNum: this.queryForms.payOrderNum,
      supplierIdList: this.queryForms.supplierId,
      page: this.tableForms.pageIndex,
      pageSize: this.tableForms.pageSize
    }
    // return
    this.tableForms.tableLoading = true;

    this.service.afterSalesTable(datas).subscribe((res: any) => {
      this.tableForms.tableLoading = false;

      this.tableData = res.data?.records || [];
      this.tableForms.total = res.data?.total || 0;
    }, (error: any) => {
      this.tableData = [];
      this.tableForms.total = 0;
      this.tableForms.tableLoading = false;
    })
  }

  /**
   * 订单售后详情
   * @param orderNum 订单号
   */
  async getOrderModelTable(orderNum: number) {
    try {
      const params = {
        orderNum: orderNum,
        page: 1,
        pageSize: 999
      }
      const { data }: any = await this.service.getOrderTableData(params);
      this.modelTableData = data || [];
    } catch {
      // console.log('error');
    }
  }

  // 查询
  queryTable() {
    this.tableForms.pageIndex = 1;
    this.loadTableData();
  }
  // 重置
  resetTable() {
    for (let key in this.queryForms) {
      if (Object.prototype.toString.call(this.queryForms[key]) === '[object Array]') {
        this.queryForms[key] = [];
      } else {
        this.queryForms[key] = '';
      }
    }
    this.queryForms.payType = '';

    this.tableForms.pageIndex = 1;
    this.loadTableData();
  }

  // 导出
  exportTableData() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let datas: any = {
          stateList: this.queryForms.stateList,
          createTimeStart: this.queryForms.createTime.length ? this.formatDate(this.queryForms.createTime[0]) : '',
          createTimeEnd: this.queryForms.createTime.length ? this.formatDate(this.queryForms.createTime[1]) : '',
          refundCreateTime: this.queryForms.refundTime.length ? this.formatDate(this.queryForms.refundTime[0]) : '',
          refundEndTime: this.queryForms.refundTime.length ? this.formatDate(this.queryForms.refundTime[1]) : '',
          payType: this.queryForms.payType,
          payOrderNum: this.queryForms.payOrderNum,
          supplierIdList: this.queryForms.supplierId, // 货主
          page: 1,
          pageSize: 1000000
        }
        for (let key in datas) {
          if (datas[key] === null) {
            datas[key] = '';
          }
    
          if (Array.isArray(datas[key])) {
            datas[key] = datas[key].length ? datas[key].join(',') : '';
          }
        }
    
        this.exportLoading = true;
        const res: any = await this.service.afterSalesExportTable(datas);
        this.exportLoading = false;
        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '售后明细');
        } else {
          this.message.error(res.message || '导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.pageIndex = index;
    this.loadTableData();
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.pageIndex = 1;
    this.tableForms.pageSize = sizeNum;
    this.loadTableData();
  }

  showModal(orderNum: any) {
    this.modelTitle = '订单 ' + orderNum + ' 的售后详情' || '';
    this.isVisible = true;

    this.getOrderModelTable(orderNum)
  }

  handleOk(): void {
    this.isVisible = false;
  }
  
  handleCancel(): void {
    this.isVisible = false;
  }
}
